package ptij.ADSL.pn.ATUC;

import ptolemy.kernel.*;
import ptolemy.kernel.util.*;
import ptolemy.data.*;
import ptolemy.data.expr.*;
import ptolemy.actor.*;

import ptij.ADSL.common.MuxDataFrame;

public class MuxSyncRx extends TypedAtomicActor {

    /* Input Ports */
    public TypedIOPort input;
    
    /* Output Ports */
    public TypedIOPort LS0;
    public TypedIOPort dataRx;

    public Parameter S;    
    
    public MuxSyncRx(TypedCompositeActor container, String name) throws
        NameDuplicationException, IllegalActionException {
        super(container, name);
    
        input = new TypedIOPort(this, "input", true, false);
	input.setTypeEquals(ObjectToken.class);
		
	LS0 = new TypedIOPort(this, "LS0", false, true);
	LS0.setTypeEquals(ObjectToken.class);
	
	dataRx = new TypedIOPort(this, "dataRx", false, true);
	dataRx.setTypeEquals(IntToken.class);

	S = new Parameter(this, "S", new IntToken(1));		
    }

    public void fire() throws IllegalActionException {

	_receiveData();
	
    }

    public void initialize() throws IllegalActionException {
        super.initialize();

	_frameCounter = 0;

	IntToken it = (IntToken) S.getToken();
	_S = it.intValue();
    }

    private void _receiveData() throws IllegalActionException {
        ObjectToken ot = (ObjectToken) input.get(0);
	MuxDataFrame mf = (MuxDataFrame) ot.getValue();

	if(_frameCounter == 0) {
	    System.out.println("$$ ATUC $$ Received FAST Frame");
	    mf.print();
	}
	else {
	    System.out.println("$$ ATUC $$ Received Interleaved Frame");
	    mf.print();
	}
	System.out.print("\n");
        _frameCounter = (_frameCounter + 1) % (_S + 1);

	int [] data = mf.getLS0();
	if(data.length != 0) {
	    dataRx.send(0, new IntToken(0));
	    LS0.send(0, new ObjectToken(data));	    
	}
    }

    private int _frameCounter;
    private int _S;
}
